package com.pomelo.tiku.activities

import android.app.Dialog
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import com.gyf.immersionbar.ImmersionBar
import com.pomelo.tiku.R
import com.pomelo.tiku.events.NetWorkChangeEvent
import com.pomelo.tiku.interfaces.IView
import com.pomelo.tiku.views.CommonToast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

open class BaseActivity : FragmentActivity(), IView {
    private var dialog: Dialog? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_base)
        initBar()
        if (!EventBus.getDefault().isRegistered(this@BaseActivity)) {
            EventBus.getDefault().register(this@BaseActivity)
        }

    }

    override fun onResume() {
        super.onResume()

    }

    protected fun showLoadingDialog() {
        if(dialog == null) {
            dialog = Dialog(this@BaseActivity)
        }
        dialog!!.setContentView(R.layout.loading_dialog_layout)
        dialog?.show()
    }

    protected  fun stopLoadingDialog() {
        if (dialog != null && dialog!!.isShowing) {
            dialog!!.dismiss()
        }
    }

    /**
     * 设置状态栏
     */
    protected fun initBar() {
        ImmersionBar.with(this)
            .transparentBar()             //透明状态栏和导航栏，不写默认状态栏为透明色，导航栏为黑色（设置此方法，fullScreen()方法自动为true）
            .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
            .fullScreen(false)
            .init()

    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun getNetWorkChangeEvent(event: NetWorkChangeEvent) {
       if(!event.netStatus) {
           CommonToast.show(this@BaseActivity,"网络已断开")
       }
    }

    override fun onDestroy() {
        super.onDestroy()

        if (EventBus.getDefault().isRegistered(this@BaseActivity)) {
            EventBus.getDefault().unregister(this@BaseActivity)
        }
    }

    override fun showLoading() {
        showLoadingDialog()
    }

    override fun stopLoading() {
        stopLoadingDialog()
    }
}